from flask import jsonify
from flask.views import MethodView
from ..auth import auth_required
from flask_login import current_user
from app.models.user import User
from app.extensions import db
from ..forms import UserResetPassword
import random


class UserAPI(MethodView):
    decorators = [auth_required]

    # 获取用户信息
    def get(self):
        data = current_user.to_dict()
        return jsonify(success=True, data=data)

    # 修改用户密码
    def post(self):
        form = UserResetPassword()
        if form.validate_on_submit():
            with db.auto_commit():
                current_user.password = form.new_password.data
            return jsonify(success=True, data=current_user.to_dict())

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)

